export default {
  props: {
    localdata: {
      type: [Array, Object],
      default () {
        return []
      }
    },
    value: {
      type: [Array, String, Number],
      default () {
        return []
      }
    },
    modelValue: {
      type: [Array, String, Number],
      default () {
        return []
      }
    },
    preload: {
      type: Boolean,
      default: false
    },
    stepSearch: {
      type: Boolean,
      default: true
    },
    map: {
      type: Object,
      default () {
        return {
          text: "text",
          value: "value"
        }
      }
    },
    loadUrl: {
      type: String,
      default: ''
    },
    level: {
      type: Number,
      default: 5
    },
  },
  data() {
    return {
      loading: false,
      errorMessage: '',
      loadMore: {
        contentdown: '',
        contentrefresh: '',
        contentnomore: ''
      },
      dataList: [],
      selected: [],
      selectedIndex: 0,

      inputSelected: [],
    }
  },
  computed: {
    dataValue() {
      let isModelValue = Array.isArray(this.modelValue) ? (this.modelValue.length > 0) :
        (this.modelValue !== null || this.modelValue !== undefined);
      return isModelValue ? this.modelValue : this.value;
    },
    hasValue() {
      if (typeof this.dataValue === 'number') {
        return true;
      }
      return (this.dataValue != null) && (this.dataValue.length > 0);
    }
  },
  created() {
    this.$watch(() => {
      var al = [];
      ['value',
        'modelValue',
        'localdata'
      ].forEach(key => {
        al.push(this[key])
      });
      return al;
    }, (newValue, oldValue) => {
      let needReset = false;
      for (let i = 2; i < newValue.length; i++) {
        if (newValue[i] != oldValue[i]) {
          needReset = true;
          break;
        }
      }

      this.onPropsChange();
    })
    this._treeData = [];
  },
  methods: {
    async loadAddressData(parentId) {
      this.loading = true;
      return new Promise((resolve, reject) => {
        http.post(this.loadUrl, {
          parentId: parentId
        }).then((res) => {
          let result = res.result || [];
          resolve(result);
        }).finally(() => {
          this.loading = false;
        })
      })
    },
    async getTreeChildren(inputValue, result) {
      this.selected = [];
      let inputValueList = inputValue || [];
      for (var i = 0; i < inputValueList.length; i++) {
        let value = inputValueList[i];
        let addressData = await this.loadAddressData(value);
        if (addressData.length > 0) {
          addressData.forEach(item => {
            item.parent_value = value;
            let hasTreeData = result.filter(hasItem => item.value === hasItem.value) || []
            if (hasTreeData.length === 0) {
              result.push(item);
            }
          })
        }
        result.forEach(item => {
          if (value === item.value) {
            this.selected.push({
              text: item.text,
              value: item.value,
            });
          }
        })
      }
      this.$nextTick(() => {
        this.inputSelected = this.selected.slice(0);
      })
    },

    onPropsChange() {
      this._treeData = [];
    },

    // 填充 pickview 数据
    async loadData() {
      this.loadLocalData();
    },

    // 加载本地数据
    async loadLocalData() {
      this._treeData = [];
      this._extractTree(this.localdata, this._treeData);

      this.getTreeChildren(this.dataValue, this._treeData);

      let inputValue = this.dataValue;
      if (this.judgeNull(inputValue)) {
        return;
      }

      let selectedValue = '';
      if (Array.isArray(inputValue)) {
        let inputSelectedValue = inputValue[inputValue.length - 1];
        if (typeof inputSelectedValue === 'object' && inputSelectedValue[this.map.value]) {
          selectedValue = inputSelectedValue[this.map.value];
        }
      }

      // this.selected = this._findNodePath(selectedValue, this.localdata);
    },

    _updateBindData(node) {
      const {
        dataList,
        hasNodes
      } = this._filterData(this._treeData, this.selected);

      let isleaf = this._stepSearh === false && !hasNodes;

      if (!this.judgeNull(node)) {
        node.isleaf = isleaf;
      }

      this.dataList = dataList;
      this.selectedIndex = dataList.length - 1;

      if (!isleaf && this.selected.length < dataList.length) {
        this.selected.push({
          value: null,
          text: "请选择"
        });
      }

      return {
        isleaf,
        hasNodes
      };
    },

    _filterData(data, paths) {
      let dataList = [];
      let hasNodes = true;

      dataList.push(data.filter((item) => {
        return (item.parent_value === null || item.parent_value === undefined || item.parent_value === '');
      }))
      for (let i = 0; i < paths.length; i++) {
        let value = paths[i].value;
        let nodes = data.filter((item) => {
          return item.parent_value === value
        })

        if (nodes.length) {
          dataList.push(nodes);
        } else {
          hasNodes = false;
        }
      }

      return {
        dataList,
        hasNodes
      };
    },

    _extractTree(nodes, result, parent_value) {
      let list = result || [];
      let valueField = this.map.value;
      for (let i = 0; i < nodes.length; i++) {
        let node = nodes[i];

        let child = {};
        for (let key in node) {
          if (key !== 'children') {
            child[key] = node[key];
          }
        }
        if (parent_value !== null && parent_value !== undefined && parent_value !== '') {
          child.parent_value = parent_value;
        }
        result.push(child);

        let children = node.children;
        if (!this.judgeNull(children)) {
          this._extractTree(children, result, node[valueField]);
        }
      }
    },

    _findNodePath(key, nodes, path = []) {
      let textField = this.map.text;
      let valueField = this.map.value;
      for (let i = 0; i < nodes.length; i++) {
        let node = nodes[i];
        let children = node.children;
        let text = node[textField];
        let value = node[valueField];

        path.push({
          value,
          text
        });

        if (value === key) {
          return path;
        }

        if (!this.judgeNull(children)) {
          const p = this._findNodePath(key, children, path);
          if (p.length) {
            return p;
          }
        }

        path.pop();
      }
      return [];
    },

    judgeNull(val) {
      return val === undefined || val === null || (val === '' && val.length === 0) || JSON.stringify(val) === '{}';
    },
  }
}
